package com.lc.projects.unit.thread.part07.test1;

import java.util.Date;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;

public class Test8 {
	public static void main(String[] args) {
		int[] array = new int[1000];
		ForkJoinPool pool = new ForkJoinPool();
		Task8 task = new Task8("name", array, 0, array.length);
		pool.invoke(task);
		pool.shutdown();
		System.out.println("Main:End.");
	}
}


abstract class MyWorkerTask extends ForkJoinTask<Void>{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String name;
	
	
	public MyWorkerTask(String name) {
		super();
		this.name = name;
	}
	
	

	public String getName() {
		return name;
	}



	public void setName(String name) {
		this.name = name;
	}



	@Override
	public Void getRawResult() {
		return null;
	}

	@Override
	protected void setRawResult(Void value) {
	}

	@Override
	protected boolean exec() {
		Date startDate = new Date();
		compute();
		Date finishDate = new Date();
		long diff = finishDate.getTime() - startDate.getTime();
		System.out.println("MyWorkerTask:"+ name + " "+diff + " milliseconds.");
		return true;
	}
	
	public abstract void compute();
}


class Task8 extends MyWorkerTask{

	
	private int[] array;
	private int start, end;
	
	

	public Task8(String name, int[] array,int start, int end) {
		super(name);
		this.array = array;
		this.start = start;
		this.end  = end;
	}

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void compute() {
		if(end - start > 100){
			int mid = (end+start)/2;
			Task8 task1 = new Task8(this.getName()+"1", array, start, mid);
			Task8 task2 = new Task8(this.getName()+"2", array, mid, end);
			invokeAll(task1,task2);
		}else{
			for (int i = start; i < end; i++) {
				array[i]++;
			}
			
			try {
				TimeUnit.MILLISECONDS.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
	
}